<template>
  <!-- 评价模板管理  -->
  <div>
    <InnerBreadcrumb v-model="indexKey" :path="breadPath" :showBack="true"/>
    <div class="edu-page-warp" v-if="indexKey === '1'">
      <condition-card @reset="reset" @search="searchList" :label-width="labelWidth" style="margin-bottom: 20px;">
        <el-row :gutter="20">
          <!-- 评价类型 -->
          <el-col :span="8">
            <el-form-item :label="$t('评价类型')">
              <el-select v-model="queryParams.type" style="width: 100%;">
                <el-option
                  v-for="item in evaluationTypeList"
                  :key="item.code"
                  :label="item.typeName"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>

      <!-- 表格card -->
      <el-card shadow="never">
        <div class="edu-page-title">{{title}}</div>
        <div class="edu-opertion-bar">
          <div class="float-left">
          <KeywordInput
              v-model="queryParams.name"
              :placeholder="$t('输入评价模板名称')"
              @enter="searchList"/>
          </div>
          <div class="float-right">
            <el-button type="danger" @click="batchDeleteClick()">{{$t('message.delete')}}</el-button>
            <el-button type="primary" @click="exportData()">{{$t('message.export')}}</el-button>
            <el-button type="primary" @click="addClick()">{{$t('message.add')}}</el-button>
          </div>
        </div>
        <!-- 主页表格 -->
        <edu-table :url="url" ref="mainTable" :order="true" :selection="true">
          <edu-table-column :label="$t('评价类型')">
            <template slot-scope="scope">
              <span v-if="scope.row.type === 1">评教</span>
              <span v-if="scope.row.type === 2">评学</span>
              <span v-if="scope.row.type === 3">过程评价</span>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('评价模板名称')" prop="name" min-width="160px"></edu-table-column>
          <edu-table-column :label="$t('备注')" prop="remark"></edu-table-column>
          <edu-table-column :label="$t('题目维护')">
            <template slot-scope="scope">
              <el-button type="text" @click.stop="maintainTopicClick(scope.row)">{{$t('题目维护')}}</el-button>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('message.operating')" min-width="160px">
            <template slot-scope="scope">
              <el-button type="text" @click.stop="previewClick(scope.row)">{{$t('预览')}}</el-button>
              <el-button type="text" @click.stop="copyClick(scope.row)">{{$t('复制')}}</el-button>
              <el-button type="text" @click.stop="editClick(scope.row)">{{$t('编辑')}}</el-button>
              <el-button type="text" @click.stop="deleteClick(scope.row)">{{$t('删除')}}</el-button>
            </template>
          </edu-table-column>
        </edu-table>
        <edu-dialog
          :title="dialogTitle"
          ref="templateDialog"
          :width="'40%'"
          :showFooter="false"
          :showButtons="false"
          @close="templateDialogClose">
          <edu-form :model="templateForm" :rules="rules" ref="templateForm" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item :label="$t('评价类型')" prop="type">
                  <el-select v-model="templateForm.type" :disabled="ifEdit" style="width: 100%;">
                    <el-option
                      v-for="item in evaluationTypeList"
                      :key="item.code"
                      :label="item.typeName"
                      :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="$t('评价模板名称')" prop="name">
                  <el-input v-model="templateForm.name" maxlength="32"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="$t('message.remark')" prop="remark">
                  <el-input type="textarea" :rows="7" maxlength="500" v-model="templateForm.remark"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </edu-form>
          <div class="dialog-footer" style="text-align: right;">
            <el-button @click="templateDialogClose">{{$t('message.cancel')}}</el-button>
            <el-button type="primary" @click="submit">{{$t('message.confirm')}}</el-button>
          </div>
        </edu-dialog>
        <edu-export-dialog :disabled="exportButton" :title="$t('message.prompt')" ref="downloadRef" :data="exportResult"></edu-export-dialog>
      </el-card>
    </div>
    <div v-if="indexKey === '2'">
      <QuestionsPreview
        :data="questionList"
        :typeTitle="typeTitle"
        :title="childTitle"
        :pageType="'maintain'"
        :exportShow="false"
        :tmpComeIn="true"
        :maintainShow="maintainShow"
        @goToMaintain="goToMaintain"
        @getChildSelect="getChildSelect"
        :currentSelcetSortList="selectMaintainSortList">
      </QuestionsPreview>
    </div>
    <div v-if="indexKey === '3'">
      <QuestionsPreview
        :data="questionList"
        :typeTitle="'预览'"
        :title="childTitle"
        :pageType="'preview'"
        :maintainShow="false"
        :tmpComeIn="true">
      </QuestionsPreview>
    </div>
    <div v-if="indexKey === '4'">
      <QuestionnaireMaintain
        :typeName="currentTypeName"
        :questionList="questionList"
        @goToPrev="goToPrev"
        @removeCurrentSort="removeCurrentSort"
        :ifWithDrawMaintan="ifWithDrawMaintan"
        :fatherSelcetSortList="selectMaintainSortList">
      </QuestionnaireMaintain>
    </div>
  </div>
</template>
<script>
import QuestionsPreview from './component/QuestionnairePreview/QuestionsPreview'
import QuestionnaireMaintain from './component/QuestionnaireMaintain'
import templateApi from 'common/src/api/teachingEvaluation/template'
import baseUrl from 'common/src/api/teachingEvaluation/env'
export default {
  components: {
    QuestionsPreview,
    QuestionnaireMaintain
  },
  data() {
    return {
      url: `${baseUrl}/template/listTemplate`,
      title: '评价模板列表',
      dialogTitle: '新增评价模板',
      typeTitle: '课程评价题目维护',
      currentTypeName: '课程',
      childTitle: '',
      ifEdit: false,
      labelWidth: '120px',
      exportButton: false,
      exportResult: null,
      templateForm: {
        type: '',
        name: '',
        remark: ''
      },
      queryParams: {
        type: '',
        name: ''
      },
      questionList: [],
      statusList: [
        {
          statusName: '未提交',
          code: 'code1'
        },
        {
          statusName: '已提交',
          code: 'code2'
        }
      ],
      evaluationTypeList: [
        {
          typeName: '评教',
          code: 1
        },
        {
          typeName: '评学',
          code: 2
        },
        {
          typeName: '过程评价',
          code: 3
        }
      ],
      rules: {
        type: [
          { required: true, message: '请选择评价类型', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请填写模板名称', trigger: 'blur' }
        ]
      },
      indexKey: '1',
      breadPath: {
        label: this.$t('评价模板管理'),
        key: "1",
        children: [
          {
            key: "2",
            label: this.$t('题目维护'),
            children: [
              {
                key: "4",
                label: this.$t('维护')
              }
            ]
          },
          {
            key: "3",
            label: this.$t('预览')
          }
        ]
      },
      selectMaintainSortList: [], // 选择的要维护的题目sortList
      maintainShow: true,
      ifWithDrawMaintan: false
    }
  },
  mounted() {
    this.searchList()
  },
  methods: {
    // 查询
    searchList() {
      this.$refs.mainTable.pageNum = 1;
      this.$refs.mainTable.search(this.queryParams);
    },
    removeCurrentSort(value) {
      this.selectMaintainSortList.splice(this.selectMaintainSortList.indexOf(value.sort), 1)
      // console.log('removeCurrentSort', value)
    },
    // 重置查询参数
    reset() {
      for (const key in this.queryParams) {
        this.queryParams[key] = "";
      }
      this.searchList()
    },
    // 编辑点击
    editClick(row) {
      let param = {
        id: row.id
      }
      templateApi.validTemplate(param).then(res => {
        // 0:未被引用 1：已被引用但未发布 2：引用且发布 3：引用且撤销
        if (res.data == '2') {
          this.$message.error('模板已被引用且问卷已发布');
        } else {
          this.dialogTitle = '编辑评价模板';
          this.ifEdit = true;
          this.$refs.templateDialog.open();
          this.templateForm = JSON.parse(JSON.stringify(row));
        }
      })
    },
    // 题目维护点击
    maintainTopicClick(row) {
      if (row.type === 3) {
        this.typeTitle = '过程评价题目维护'
      } else {
        this.typeTitle = '课程评价题目维护'
      }
      let param = {
        id: row.id
      }
      templateApi.validTemplate(param).then(res => {
        if (res.data == '2') {
          this.maintainShow = false
        } else {
          this.maintainShow = true
        }
        if (res.data == '3') {
          this.ifWithDrawMaintan = true
        } else {
          this.ifWithDrawMaintan = false
        }
        this.$router.push({
          query: {
            row: row,
            ifProcess: row.type === 3 ? true : false
          }
        })
        this.childTitle = row.name
        templateApi.getQuestionDetail(param).then(res => {
          if (res.code === 200) {
            this.questionList = res.data
            this.questionList.forEach(item => {
              // titleType: {1.单选 2.多选 3.问答}
              if (item['options']) {
                item['options'] = JSON.parse(item['options'])
              }
              if (item['titleType'] == '1') {
                item['questionTypeName'] = '单选题';
              } else if (item['titleType'] == '2') {
                item['questionTypeName'] = '多选题';
              } else if (item['titleType'] == '3') {
                item['questionTypeName'] = '问答题';
              }
            })
          }
        })
        this.indexKey = '2'
      })
    },
    // 预览
    previewClick(row) {
      this.$router.push({
        query: {
          row: row,
          ifProcess: row.type === 3 ? true : false
        }
      })
      let param = {
        id: row.id
      }
      this.childTitle = row.name
      templateApi.getQuestionDetail(param).then(res => {
        if (res.code === 200) {
          this.questionList = res.data
          this.questionList.forEach(item => {
            // titleType: {1.单选 2.多选 3.问答}
            if (item['options']) {
              item['options'] = JSON.parse(item['options'])
            }
          })
        }
      })
      this.indexKey = '3'
    },
    // 删除点击
    deleteClick(row) {
      let param = [row.id];
      this.$confirm(this.$t('message.areYouSureDelete'), this.$t("message.prompt"), {
        confirmButtonText: this.$t("message.confirm"),
        cancelButtonText: this.$t("message.cancel"),
        type: "warning"
      }).then(() => {
        templateApi.deleteTemplate(param).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.searchList();
          }
        })
      });
    },
    // 批量删除
    batchDeleteClick() {
      let checkData = this.$refs.mainTable.getCheckData()
      if (checkData.length < 1) {
        this.$message.error(this.$t('请选择需要删除的数据'));
      } else {
        let param = checkData.map(item => {
          return item.id
        });
        this.$confirm(this.$t('message.areYouSureDelete'), this.$t("message.prompt"), {
          confirmButtonText: this.$t("message.confirm"),
          cancelButtonText: this.$t("message.cancel"),
          type: "warning"
        }).then(() => {
          templateApi.deleteTemplate(param).then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功');
              this.searchList();
            }
          })
        });
      }
    },
    // 新增点击
    addClick() {
      this.dialogTitle = '新增评价模板';
      this.ifEdit = false;
      this.$refs.templateDialog.open();
    },
    // 复制点击
    copyClick(row) {
      let param = {
        id: row.id
      }
      templateApi.copyTemplate(param).then(res => {
        if (res.code === 200) {
          this.$message.success('复制成功')
          this.searchList();
        }
      })
    },
    // 进入题目维护的页面
    goToMaintain() {
      this.indexKey = '4';
    },
    // 题目维护 选择的题目
    getChildSelect(value) {
      this.selectMaintainSortList = value
    },
    // 返回上一级
    goToPrev() {
      this.indexKey = '2';
    },
    // 重置表单
    resetTemplateForm() {
      this.templateForm = {
        type: '',
        name: '',
        remark: ''
      }
    },
    // 关闭弹窗
    templateDialogClose() {
      this.resetTemplateForm()
      this.$refs.templateForm.clearValidate();
      // this.$refs.templateForm.resetFields();
      this.$nextTick(() => {
        this.$refs.templateDialog.close()
      })
    },
    // 新增/编辑提交
    submit() {
      this.$refs.templateForm.validate(valid => {
        if (valid) {
          if (!this.ifEdit) {
            templateApi.insertTemplate(this.templateForm).then(res => {
              if (res.code === 200) {
                this.$message.success('新增成功');
                this.templateDialogClose();
                this.searchList();
              }
            })
          } else {
            templateApi.updateTemplate(this.templateForm).then(res => {
              if (res.code === 200) {
                this.$message.success('编辑成功');
                this.templateDialogClose();
                this.searchList();
              }
            })
          }
        }
      })
    },
    // 导出
    exportData() {
      if (this.$refs.mainTable.getData().length <= 0) {
        this.$message.error(this.$t('result.noExportData'));
        return;
      }
      const checkDatas = this.$refs.mainTable.getCheckData();
      let param = {
        mainId: this.$route.query.id,
        name: this.$route.query.name,
        ids: []
      }
      if (checkDatas.length > 0) {
        param.ids = checkDatas.map(item => {
          return item.id
        })
      }
      param.type = this.queryParams.type
      param.name = this.queryParams.name
      this.exportResult = null;
      this.$refs.downloadRef.open();
      this.exportButton = true;
      templateApi.exportTemplateListData(param).then(res =>{
        if (res.code == 200) {
          let path = `${baseUrl}/template/downFile?path=${res.data}`
          // console.log('res', res)
          window.location.href = path;
          this.$message.success(this.$t('result.exportSuccessfully'));
          this.$refs.downloadRef.close();
        } else {
          this.$refs.downloadRef.close();
          this.exportButton = false;
        }
      })
    }
  },
  watch: {
    indexKey(value) {
      if (value === '1') {
        this.$nextTick(() => {
          this.searchList()
        })
      } else if (value === '2' || value === '3') {
        // let param = {
        //   id: this.$route.query.row.id
        // }
        // templateApi.getQuestionDetail(param).then(res => {
        //   if (res.code === 200) {
        //     this.questionList = res.data
        //     this.questionList.forEach(item => {
        //       // titleType: {1.单选 2.多选 3.问答}
        //       if (item['options']) {
        //         item['options'] = JSON.parse(item['options'])
        //       }
        //       if (item['titleType'] == '1') {
        //         item['questionTypeName'] = '单选题';
        //       } else if (item['titleType'] == '2') {
        //         item['questionTypeName'] = '多选题';
        //       } else if (item['titleType'] == '3') {
        //         item['questionTypeName'] = '问答题';
        //       }
        //     })
        //   }
        // })
        this.selectMaintainSortList = []
      }
    }
  }
}
</script>
